import time
from flask import Blueprint, request, send_from_directory

from utils.response import success, fail
from utils.rate_limit_decorator import rate_limit

from config import API_COOIKE

from services.user_service import user_info_service, get_user_avatar_path, upload_user_info_service

user = Blueprint('user', __name__)

@user.route('/get_user_info', methods=['POST'])
def get_user_info():
    if not request.is_json:
        return fail('request body must be json')
    params = request.get_json()
    # 返回一个字典，包含一个键值对，键为'result'，值为123
    if 'user_id' not in params or 'cookie' not in params:
        return fail('params is not required')
    user_id = params['user_id']
    cookie = params['cookie']
    result = user_info_service(user_id, cookie)
    if result is None:
        return fail('用户id或cookie无效')
    return success(result)

@user.route('/get_user_info_no_cookie', methods=['POST'])
@rate_limit(interval=30)
def get_user_info_no_cookie():
    if not request.is_json:
        return fail('request body must be json')
    params = request.get_json()
    # 返回一个字典，包含一个键值对，键为'result'，值为123
    if 'user_id' not in params:
        return fail('params is not required')
    user_id = params['user_id']
    cookie = API_COOIKE
    result = user_info_service(user_id, cookie)
    if result is None:
        return fail('用户id或cookie无效')
    return success(result)

@user.route('/<filename>')
def show_user_avatar(filename):
    avatar_folder = get_user_avatar_path()
    # 安全校验：仅允许 jpg/png 格式
    if not (filename.endswith('.jpg') or filename.endswith('.png')):
        return 'Invalid file type'
    return send_from_directory(avatar_folder, filename)

# @user.route('/upload_user_info', methods=['POST'])
# def upload_user_info():
#     if not request.is_json:
#         return fail('request body must be json')
#     # 返回一个字典，包含一个键值对，键为'result'，值为123
#     data = request.get_json()
#     if 'ok' not in data:
#         return fail('json is required')
#     if not data['ok'] or not data['data'] or not data['data']['user']:
#         return fail('upload data error')
#     result = upload_user_info_service(data['data']['user'])
    
#     return success(result)
